package tech.yunland.shop.web;

import com.alibaba.fastjson.JSON;
import com.moyuer.bsf.common.ImageUtil;
import com.moyuer.bsf.common.Pagination;
import com.moyuer.bsf.common.PinYinUtil;
import com.moyuer.bsf.web.controller.BaseController;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import tech.yunland.shop.domain.model.GoodsPackage;
import tech.yunland.shop.domain.model.GoodsPackageEntry;
import tech.yunland.shop.domain.model.GoodsPictures;
import tech.yunland.shop.domain.service.GoodsPackageService;

import javax.imageio.ImageIO;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * 优惠活动控制器
 *
 * @author 王睿智 <geekrize@gamil.com>
 */
@RestController
@RequestMapping("/goods_package")
public class GoodsPackageController extends BaseController {

    @Value("${upload.save.dir}")
    private String uploads_dir;

    @Autowired
    private GoodsPackageService goodsPackageService;

    /**
     * 保存活动
     *
     * @param goodsPackage
     */
    @RequestMapping(value = "/", method = RequestMethod.POST)
    public void saveOrUpdate(@RequestBody @Valid GoodsPackage goodsPackage) {
        // 输出日志
        logger.info(JSON.toJSONString(goodsPackage, true));

        // 判断组织
        if (goodsPackage.getOrgan() == null) {
            goodsPackage.setOrgan(primaryOrgan);
        }

        // 判断创建人
        if (goodsPackage.getCreator() == null) {
            goodsPackage.setCreator(this.currentUser);
        }

        // 判断活动名称是否存在
        List<GoodsPackage> existsGoodsPackage = goodsPackageService.getList(goodsPackage.getName(), primaryOrganId);
        if (existsGoodsPackage != null) {
            if (existsGoodsPackage.size() > 1) {
                throw new RuntimeException("同名优惠活动已存在");
            } else if (existsGoodsPackage.size() == 1) {
                GoodsPackage t = existsGoodsPackage.get(0);
                if (!t.getId().equals(goodsPackage.getId())) {
                    throw new RuntimeException("同名优惠活动已存在");
                }
            }
        }

        // 分录对象赋值
        if (goodsPackage.getEntries() != null) {
            for (GoodsPackageEntry entry : goodsPackage.getEntries()) {
                entry.setOwner(goodsPackage);
            }
        }

        // 名称缩写
        goodsPackage.setSpell(PinYinUtil.getFirstSpell(goodsPackage.getName()));
        // 调用Service保存
        goodsPackageService.saveOrUpdate(goodsPackage);
        // 保存日志
        saveLog("优惠活动:[" + goodsPackage.getName() + "]保存成功！");

    }

    /**
     * 根据主键获取活动
     *
     * @param id
     * @Return GoodsPackage
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public GoodsPackage get(@PathVariable String id) {
        goodsPackageService.updateRate(id); // 增加权重
        return goodsPackageService.get(id);
    }

    /**
     * 根据主键删除活动
     *
     * @param id
     * @Return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public void delete(@PathVariable String id) {

        GoodsPackage goodsPackage = goodsPackageService.get(id);

        goodsPackageService.delete(id);

        saveLog("优惠活动:[" + goodsPackage.getName() + "]删除成功！");

    }

    /**
     * 分页读取优惠活动
     *
     * @param param  参数
     * @param states 状态集
     * @param page   起始索引
     * @param rows   每页数量
     * @return
     * @Return Pagination<GoodsPackage>
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public Pagination<GoodsPackage> getResultInfos(@RequestParam(required = false) String param,
                                                   @RequestParam(required = false) List<Integer> states,
                                                   @RequestParam(required = false) Integer page,
                                                   @RequestParam(required = false) Integer rows) {

        Pagination<GoodsPackage> result = new Pagination<GoodsPackage>(page, rows);
        int startIdx = result.getStartIdx();

        int count = goodsPackageService.getResultSize(param, states, organIds);
        List<GoodsPackage> records = goodsPackageService.getResultInfos(param, states, startIdx, rows, organIds);

        result.setCount(count);
        result.setRecords(records);

        return result;
    }

    /**
     * 读取指定优惠活动的所有分录
     *
     * @param ownerId 所属优惠活动标识
     * @return Set<GoodsPackageEntry>
     */
    @RequestMapping(value = "/{ownerId}/entries", method = RequestMethod.GET)
    public Set<GoodsPackageEntry> getEntries(@PathVariable String ownerId) {
        GoodsPackage owner = goodsPackageService.get(ownerId);
        return owner.getEntries();
    }

    /**
     * 读取指定分录
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/entry/{id}", method = RequestMethod.GET)
    public GoodsPackageEntry getEntry(@PathVariable String id) {
        return goodsPackageService.getEntry(id);
    }

    /**
     * 新增或修改优惠活动分录
     *
     * @param entry
     */
    @RequestMapping(value = "/entry", method = RequestMethod.POST)
    public void addOrEditEntry(@RequestBody GoodsPackageEntry entry) {
        Set<String> errorSet = new HashSet<String>();
        if (entry.getOwner() == null || entry.getOwner().getId() == null) {
            errorSet.add("没有指定所属优惠活动");
        }

        if (entry.getGoods() == null || entry.getGoods().getId() == null) {
            errorSet.add("商品不能为空");
        }

        if (entry.getQuantity() == null || BigDecimal.ZERO.equals(entry.getQuantity())) {
            errorSet.add("数量必须大于 0");
        }

        // 判断是否有重复商品
        // GoodsPackage goodsPackage =
        // goodsPackageService.get(entry.getOwner().getId());
        // for (GoodsPackageEntry goodsPackageEntry : goodsPackage.getEntries())
        // {
        // if
        // (goodsPackageEntry.getGoods().getId().equals(entry.getGoods().getId()))
        // {
        // errorSet.add("此商品已经存在于该活动！");
        // }
        // }

        if (errorSet.size() > 0) {
            throw new RuntimeException(StringUtils.join(errorSet, ", "));
        }


        // 查询是否拥有重复商品
        List<GoodsPackageEntry> goodsPackageEntry = goodsPackageService.findRepeatEntry(entry.getId(), entry.getOwner().getId(), entry.getGoods().getId());

        // 重复提示
        if (goodsPackageEntry.size() > 0) {
            throw new RuntimeException("该商品已经存于该优惠活动礼包，无法进行新增！");
//			BigDecimal quantity = BigDecimal.ZERO;
//			for (int i = 0; i < goodsPackageEntry.size(); i++) {
//				quantity=quantity.add(goodsPackageEntry.get(i).getQuantity());
//			}
//
//			GoodsPackageEntry newEntry = new GoodsPackageEntry();
//			newEntry.setGoods(entry.getGoods());
//			newEntry.setOwner(entry.getOwner());
//			newEntry.setQuantity(entry.getQuantity().add(quantity));
//
//			goodsPackageService.saveOrUpdate(newEntry);
//
//			// 删除历史分录
//			for (int i = 0; i < goodsPackageEntry.size(); i++) {
//				goodsPackageService.deleteEntry(goodsPackageEntry.get(i));
//			}

        } else {
            goodsPackageService.saveOrUpdate(entry);
        }

        goodsPackageService.saveOrUpdate(goodsPackageService.get(entry.getOwner().getId()));

        // 保存日志

//		saveLog("保存优惠活动详情 [" + packageEntry.getGoods().getName() + "]");

        // 尝试自动生成缩略图, 失败略过
        try {
            reGenMergePic(entry.getOwner().getId());
        } catch (Exception e) {
            logger.info("生成合图失败: " + e.getMessage());
        }
    }

    /**
     * 物理删除优惠活动分录
     *
     * @param id
     */
    @RequestMapping(value = "/entry/{id}", method = RequestMethod.DELETE)
    public void deleteEntry(@PathVariable String id) {
        GoodsPackageEntry entry = goodsPackageService.getEntry(id);
        goodsPackageService.deleteEntry(entry);
        // 保存日志
        saveLog("删除优惠活动详情 [" + entry.getGoods().getName() + "]");

        // 尝试自动生成缩略图, 失败略过
        try {
            reGenMergePic(entry.getOwner().getId());
        } catch (Exception e) {
            logger.info("生成合图失败: " + e.getMessage());
        }


    }

    /**
     * 从优惠活动所包含商品的缩略图, 重新为优惠活动生成合图
     *
     * @param goodsPackageId
     */
    private void reGenMergePic(String goodsPackageId) throws IOException {
        GoodsPackage goodsPackage = goodsPackageService.get(goodsPackageId);

        // 如果优惠活动有多张插图,不处理,交用户自行处理
        if (goodsPackage.getPictures() != null && goodsPackage.getPictures().size() > 1) {
            return;
        }

        if (goodsPackage.getEntries() == null || goodsPackage.getEntries().size() == 0) {
            return;
        }

        Set<BufferedImage> imageSet = new HashSet<BufferedImage>();
        String thumbPath = StringUtils.stripEnd(uploads_dir, "/") + "/thumb";

        for (GoodsPackageEntry entry : goodsPackage.getEntries()) {
            if (entry.getGoods().getPictures() == null || entry.getGoods().getPictures().size() == 0) {
                continue;
            }

            // 每个商品取一张图
            for (GoodsPictures goodsPictures : entry.getGoods().getPictures()) {
                File f = new File(thumbPath, goodsPictures.getPicture().getFileName());
                BufferedImage bufferedImage = ImageIO.read(f);
                imageSet.add(bufferedImage);
                break;
            }
        }

        BufferedImage[] images = imageSet.toArray(new BufferedImage[imageSet.size()]);
        BufferedImage mergeFourImage = new ImageUtil().mergeFour(images);

        String fileName = UUID.randomUUID().toString() + ".jpg";
        // 保存生成的大图
        ImageIO.write(mergeFourImage, "jpg", new File(uploads_dir, fileName));

        // 缩小
        BufferedImage thumbnail = Thumbnails.of(mergeFourImage).size(96, 96).asBufferedImage();
        // 裁剪
        Thumbnails.of(thumbnail).sourceRegion(Positions.CENTER, 96, 96).size(96, 96).keepAspectRatio(false)
                .toFile(new File(thumbPath, fileName));

        goodsPackageService.saveOrUpdatePicture(goodsPackageId, fileName);
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public void saveGoodsPackage(@RequestBody GoodsPackage goodsPackage){
        // 输出日志
        logger.info(JSON.toJSONString(goodsPackage, true));

        // 判断组织
        if (goodsPackage.getOrgan() == null) {
            goodsPackage.setOrgan(primaryOrgan);
        }

        // 判断创建人
        if (goodsPackage.getCreator() == null) {
            goodsPackage.setCreator(this.currentUser);
        }

        // 判断活动名称是否存在
        List<GoodsPackage> existsGoodsPackage = goodsPackageService.getList(goodsPackage.getName(), primaryOrganId);
        if (existsGoodsPackage != null && existsGoodsPackage.size() > 0) {
           if (existsGoodsPackage.size() == 1){
               GoodsPackage _goodsPackage = existsGoodsPackage.get(0);
               if (!_goodsPackage.getId().equals(goodsPackage.getId())){
                   throw new RuntimeException("同名优惠活动已存在");
               }
           }else {
               throw new RuntimeException("同名优惠活动已存在");
           }
        }

        // 名称缩写
        goodsPackage.setSpell(PinYinUtil.getFirstSpell(goodsPackage.getName()));
        // 调用Service保存
        goodsPackageService.save(goodsPackage);

        try {
            reGenMergePic(goodsPackage.getId());
        } catch (Exception e) {
            logger.info("生成合图失败: " + e.getMessage());
        }

        // 保存日志
        saveLog("优惠活动:[" + goodsPackage.getName() + "]保存成功！");
    }

    @RequestMapping(value = "/saveEntries",method = RequestMethod.POST)
    public void saveEnties(@RequestBody GoodsPackageEntry... entries){

        String ownerId = "";
        for (GoodsPackageEntry entry: entries){
            if (entry.getOwner() == null || entry.getOwner().getId() == null) {
                throw new RuntimeException("没有指定所属优惠活动");
            }

            ownerId = entry.getOwner().getId();

            if (entry.getGoods() == null || entry.getGoods().getId() == null) {
                throw new RuntimeException("商品不能为空");
            }

            if (entry.getQuantity() == null || BigDecimal.ZERO.equals(entry.getQuantity())) {
                throw new RuntimeException("数量必须大于 0");
            }

            // 查询是否拥有重复商品
            List<GoodsPackageEntry> goodsPackageEntry = goodsPackageService.findRepeatEntry(entry.getId(), entry.getOwner().getId(), entry.getGoods().getId());

            if (goodsPackageEntry.size() > 0) {
                throw new RuntimeException("该商品已经存于该优惠活动礼包，无法进行新增！");
            }

            goodsPackageService.saveOrUpdate(entry);

        }

        goodsPackageService.saveOrUpdate(goodsPackageService.get(ownerId));
        try {
            reGenMergePic(ownerId);
        } catch (Exception e) {
            logger.info("生成合图失败: " + e.getMessage());
        }

    }
}
